package com.yangit.temp.util.excel.easy.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.yangit.temp.util.excel.easy.entity.StationData;
import com.yangit.temp.util.excel.easy.service.IStationService;
import com.yangit.temp.util.excel.easy.util.StationDataReadListener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;

/**
 * 文档服务类
 */
@Controller
public class StationController {

	/**
	 *下载文件
	 * @param response
	 * @throws IOException
	 */
	@GetMapping("download")
	public void download(HttpServletResponse response) throws IOException {
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		String fileName = URLEncoder.encode("统计", "UTF-8").replaceAll("\\+", "%20");
		response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), StationData.class).sheet("统计").doWrite(data(new JSONObject()));

	}

	private List<StationData> data(JSONObject json) {
		List<StationData> list = new ArrayList<StationData>();
		int size = stationService.getCount(json);
		for (int i = 0; i < 178181; i++) {
			List<StationData> stationData = stationService.get(Integer.toString(i));
			list.addAll(stationData);
		};
		return list;
	}

	@Autowired
	IStationService stationService;


	/**
	 * 上传文件
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@PostMapping("upload")
	@ResponseBody
	public String upload(MultipartFile file) throws IOException {
		long startTime = System.currentTimeMillis();
		EasyExcel.read(file.getInputStream(), StationData.class, new StationDataReadListener()).sheet().doRead();
		long endTime = System.currentTimeMillis();
		return"success,"+(endTime-startTime);
	}


}